package com.property.demo.controller;

import com.property.demo.dto.VehicleDTO;
import com.property.demo.model.Vehicle;
import com.property.demo.service.VehicleService;
import com.property.demo.util.DTOMapper;
import com.property.demo.util.SortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/vehicles")
public class VehicleController {

    private static final Logger logger = LoggerFactory.getLogger(VehicleController.class);

    @Autowired
    private VehicleService vehicleService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllVehicles(
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String licensePlate,
            @RequestParam(required = false) String brand,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id,desc") String[] sort) {

        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));

            Page<Vehicle> vehiclePage;
            
            if (ownerId != null || licensePlate != null || brand != null || type != null || status != null) {
                vehiclePage = vehicleService.findByFilters(ownerId, licensePlate, brand, type, status, pageable);
            } else {
                vehiclePage = vehicleService.findAll(pageable);
            }

            List<VehicleDTO> vehicleDTOs = vehiclePage.getContent().stream()
                    .map(DTOMapper::toVehicleDTO)
                    .collect(Collectors.toList());

            Map<String, Object> response = new HashMap<>();
            response.put("content", vehicleDTOs);
            response.put("currentPage", vehiclePage.getNumber());
            response.put("totalItems", vehiclePage.getTotalElements());
            response.put("totalPages", vehiclePage.getTotalPages());

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<VehicleDTO> getVehicleById(@PathVariable("id") Long id) {
        Optional<Vehicle> vehicleData = vehicleService.findById(id);
        
        if (vehicleData.isPresent()) {
            VehicleDTO vehicleDTO = DTOMapper.toVehicleDTO(vehicleData.get());
            return new ResponseEntity<>(vehicleDTO, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @PostMapping
    public ResponseEntity<VehicleDTO> createVehicle(@RequestBody Vehicle vehicle) {
        try {
            logger.info("接收到创建车辆请求: {}", vehicle);

            // 检查车牌号是否已存在
            if (vehicleService.existsByLicensePlate(vehicle.getLicensePlate())) {
                logger.warn("车牌号已存在: {}", vehicle.getLicensePlate());
                return new ResponseEntity<>(HttpStatus.CONFLICT);
            }

            // 检查是否是前端提交的嵌套对象结构
            if (vehicle.getOwner() != null && vehicle.getOwner().getId() != null) {
                logger.info("检测到嵌套对象结构，正在处理...");
                logger.info("业主ID: {}", vehicle.getOwner().getId());
            } else {
                logger.warn("接收到的数据不符合预期的嵌套对象结构，可能导致保存失败");
            }

            // 记录关键字段信息
            logger.info("车牌号(licensePlate): {}", vehicle.getLicensePlate());
            logger.info("车牌号(plateNumber): {}", vehicle.getPlateNumber());
            logger.info("品牌: {}", vehicle.getBrand());
            logger.info("型号: {}", vehicle.getModel());
            logger.info("类型: {}", vehicle.getType());
            logger.info("状态: {}", vehicle.getStatus());
            
            // 确保plateNumber和licensePlate保持一致
            if (vehicle.getLicensePlate() != null && (vehicle.getPlateNumber() == null || !vehicle.getPlateNumber().equals(vehicle.getLicensePlate()))) {
                vehicle.setPlateNumber(vehicle.getLicensePlate());
                logger.info("已同步plateNumber值: {}", vehicle.getPlateNumber());
            }
            
            Vehicle savedVehicle = vehicleService.save(vehicle);
            VehicleDTO vehicleDTO = DTOMapper.toVehicleDTO(savedVehicle);

            logger.info("车辆创建成功，ID: {}", savedVehicle.getId());

            return new ResponseEntity<>(vehicleDTO, HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error("创建车辆失败", e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<VehicleDTO> updateVehicle(@PathVariable("id") Long id, @RequestBody Vehicle vehicle) {
        // 检查车牌号是否已存在于其他车辆
        Optional<Vehicle> existingVehicleWithSameLicensePlate = vehicleService.findByLicensePlate(vehicle.getLicensePlate());
        if (existingVehicleWithSameLicensePlate.isPresent() && !existingVehicleWithSameLicensePlate.get().getId().equals(id)) {
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }
        
        Vehicle updatedVehicle = vehicleService.update(id, vehicle);
        
        if (updatedVehicle != null) {
            VehicleDTO vehicleDTO = DTOMapper.toVehicleDTO(updatedVehicle);
            return new ResponseEntity<>(vehicleDTO, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deleteVehicle(@PathVariable("id") Long id) {
        try {
            vehicleService.delete(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping
    public ResponseEntity<HttpStatus> deleteAllVehicles(@RequestBody List<Long> ids) {
        try {
            vehicleService.deleteAll(ids);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<List<VehicleDTO>> getVehiclesByOwnerId(@PathVariable("ownerId") Long ownerId) {
        try {
            List<Vehicle> vehicles = vehicleService.findByOwnerId(ownerId);
            
            if (vehicles.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            
            List<VehicleDTO> vehicleDTOs = DTOMapper.toVehicleDTOList(vehicles);
            return new ResponseEntity<>(vehicleDTOs, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/check-license-plate")
    public ResponseEntity<Boolean> checkLicensePlate(@RequestParam String licensePlate) {
        boolean exists = vehicleService.existsByLicensePlate(licensePlate);
        return new ResponseEntity<>(exists, HttpStatus.OK);
    }
} 
